package com.wnhz.work.yz.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

public class MyUtils {
    public static void Load(ImageView img, String str) {
        ImageLoader.getInstance().displayImage(str,
                img);

    }

    public static String[] minus(String[] arr1, String[] arr2) {
        LinkedList list = new LinkedList();
        LinkedList history = new LinkedList();
        String[] longerArr = arr1;
        String[] shorterArr = arr2;
        //找出较长的数组来减较短的数组
        if (arr1.length > arr2.length) {
            longerArr = arr2;
            shorterArr = arr1;
        }
        for (String str : longerArr) {
            if (!list.contains(str)) {
                list.add(str);
            }
        }
        for (String str : shorterArr) {
            if (list.contains(str)) {
                history.add(str);
                list.remove(str);
            } else {
                if (!history.contains(str)) {
                    list.add(str);
                }
            }
        }

        String[] result = {};
        return (String[]) list.toArray(result);
    }

    /**
     * 更改字体大小
     *
     * @param s
     * @param f
     * @return
     */
    public static SpannableString setSpannableString(String s, float f) {
        SpannableString member = new SpannableString(s);
        member.setSpan(new RelativeSizeSpan(f), 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        return member;
    }

    /**
     * 更改字体颜色
     *
     * @param s1
     * @param color
     * @return
     */
    public static SpannableString setColotSpannableString(String s1, int color) {
        String s = s1 + "元";
        SpannableString member = new SpannableString(s);
        member.setSpan(new ForegroundColorSpan(color), 0, s1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return member;
    }

    /**
     * 正则表达式:验证身份证
     */
    public static final String REGEX_ID_CARD = "(^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$)";

    /**
     * 正则表达式:验证密码(不包含特殊字符)
     */
//    public static final String REGEX_PASSWORD = "^[a-zA-Z0-9]{6,16}$";
//    public static final String REGEX_PASSWORD = ".*[a-zA-Z].*[0-9]{6,16}$|.*[0-9].*[a-zA-Z]{6,16}$";
    public static final String REGEX_PASSWORD = "^(?![0-9]+$)[0-9A-Za-z]{6,10}$";

    /**
     * 校验密码
     *
     * @param password
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isPassword(String password) {
        return Pattern.matches(REGEX_PASSWORD, password);
    }

    /**
     * 校验身份证
     *
     * @param idCard
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isIDCard(String idCard) {
        return Pattern.matches(REGEX_ID_CARD, idCard);
    }


    public static final String NUMBER = "^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*";

    /**
     * 匹配正浮点数
     *
     * @param number
     * @return
     */
    public static boolean isNumber(String number) {
        return Pattern.matches(NUMBER, number);
    }

//    /**
//     * 验证手机格式
//     */
//    public static boolean isMobileNO(String mobiles) {
//        /*
//         * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
//		 * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
//		 * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
//		 */
//        String telRegex = "/^0?(12[0-9]|13[0-9]|15[0-9]|17[013678]|18[0-9]|14[57])[0-9]{8}$/";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
//        if (TextUtils.isEmpty(mobiles)) {
//            return false;
//        } else {
//            return mobiles.matches(telRegex);
//        }
//    }


    public static boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                /*
                BACKGROUND=400 EMPTY=500 FOREGROUND=100
                GONE=1000 PERCEPTIBLE=130 SERVICE=300 ISIBLE=200
                 */
                Log.i(context.getPackageName(), "此appimportace ="
                        + appProcess.importance
                        + ",context.getClass().getName()="
                        + context.getClass().getName());
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    Log.i(context.getPackageName(), "处于后台"
                            + appProcess.processName);
                    return true;
                } else {
                    Log.i(context.getPackageName(), "处于前台"
                            + appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }

    public static void deleteFile(File file) {
        if (file.exists()) { // 判断文件是否存在
            if (file.isFile()) { // 判断是否是文件
                file.delete(); // delete()方法 你应该知道 是删除的意思;
            } else if (file.isDirectory()) { // 否则如果它是一个目录
                File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
                for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                    deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
                }
            }
            file.delete();
        }
    }


    /**
     * 图片压缩
     *
     * @param fileUri
     * @return
     */
    public static File scal(Uri fileUri) {
        String path = fileUri.getPath();
        File outputFile = new File(path);
        long fileSize = outputFile.length();
        final long fileMaxSize = 200 * 1024;
        if (fileSize >= fileMaxSize) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
            int height = options.outHeight;
            int width = options.outWidth;

            double scale = Math.sqrt((float) fileSize / fileMaxSize);
            options.outHeight = (int) (height / scale);
            options.outWidth = (int) (width / scale);
            options.inSampleSize = (int) (scale + 0.5);
            options.inJustDecodeBounds = false;

            Bitmap bitmap = BitmapFactory.decodeFile(path, options);
            outputFile = new File(createImageFile().getPath());
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outputFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            } else {
                File tempFile = outputFile;
                outputFile = new File(createImageFile().getPath());
                copyFileUsingFileChannels(tempFile, outputFile);
            }

        }
        return outputFile;

    }

    public static Uri createImageFile() {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = null;
        try {
            image = File.createTempFile(
                    "imageFileName",
                    ".jpg",
                    storageDir);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Save a file: path for use with ACTION_VIEW intents
        return Uri.fromFile(image);
    }

    public static void copyFileUsingFileChannels(File source, File dest) {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            try {
                inputChannel = new FileInputStream(source).getChannel();
                outputChannel = new FileOutputStream(dest).getChannel();
                outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } finally {
            try {
                inputChannel.close();
                outputChannel.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 1000;
    private static long lastClickTime;

    /**
     *
     * @return true:间隔大于1秒
     */
    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    //判断小数点位数是否大于1
    public static boolean isBiggerTwo(double num){
        int nowNum = (num + "").length() - (num + "").indexOf(".") - 1;
        if (nowNum > 2){
            return true;
        }
        return false;
    }

    public static double doubleRound(double douNum){
        BigDecimal b = new BigDecimal(douNum);
        //保留2位小数
        double f1 = b.setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue();
        return f1;
    }

    public static boolean  isEqual(double a,double b){
        BigDecimal data1 = new BigDecimal(a);
        BigDecimal data2 = new BigDecimal(b);
        if (data1.compareTo(data2) == -1){//data1 < data2
            return false;
        }else if (data1.compareTo(data2) == 0){//data1 = data2
            return true;
        }else {//data1 > data2
            return false;
        }
    }
}
